<template>
    <div class="">
        <el-dialog  :title="addForm.id>0 ? '修改居民':'添加居民'" :close-on-click-modal="false" style="width: 650px;" v-model="dialogVisible" :before-close="handleClose">
            <el-form :rules="rules" ref="ruleFormRef" :model="addForm" class="elform" label-width="auto">
                <el-form-item label="图片" class="photo">
                    <el-upload class="avatar-uploader" :headers="headers" :action="uploadUrl" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="addForm.photo" :src="baseUrl + addForm.photo" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>

                <el-form-item label="姓名" prop="name">
                    <el-input v-model="addForm.name" />
                </el-form-item>

                <el-form-item label="管辖范围">
                    <BuildSelect @update="getbuilding" :defaultValue="buildid" :checkStrictly="false" :multiple="true"></BuildSelect>
                </el-form-item>

                <el-form-item label="职员类型">
                    <el-select clearable v-model="addForm.type" style="width:120px" placeholder="请选择状态">
                        <el-option v-for="item in staffsType" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="性别">
                    <el-radio-group v-model="addForm.sex"  >
                        <el-radio :value="1" size="large">男</el-radio>
                        <el-radio :value="2" size="large">女</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="身份证号" class="right">
                    <el-input v-model="addForm.cardid" />
                </el-form-item>
                <el-form-item label="联系电话" class="right">
                    <el-input v-model="addForm.mobile" />
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUserInfo">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script lang='ts' setup>
import { ref, reactive, onMounted } from "vue"
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import BuildSelect from "./BuildSelect.vue"
import type { FormInstance, FormRules } from 'element-plus'
import {getstafftype,staffadd} from '../service/staffs/staffs'
import {stafftype} from '../service/staffs/type'
import {useStore} from "../store/index"
import { storeToRefs } from "pinia"
import { map } from "echarts/types/src/export/api/util.js"

const store = useStore()

const { token } = storeToRefs(store)
const headers = {Authorization: token.value}
const uploadUrl = import.meta.env.VITE_BASE_URL + "upload/add";
const baseUrl = import.meta.env.VITE_IMG_URL

const porps =  defineProps(["addForm"])

const getbuilding = (val:any)=>{
    console.log(val);
    let arr:any = []
    val.forEach((element:any) => {
        arr.push(element[element.length-1])
    });
    console.log(arr);
    let buildid =arr.map((item:number)=>{
        return {buildid:item }
    })
    addForm.building = buildid
}

const staffsType = ref<any[]>([])
 const getstafftypes  = async()=>{
    let res =await getstafftype()
    staffsType.value = res.data.list
}
//提交
const addUserInfo =async () => {
    let res:any =await staffadd(addForm).catch(()=>{})
    console.log(res);
    if (res.errCode == 10000) {
        ElMessage.success(res.errMsg)
        emit('update',true)
        dialogVisible.value = false
    } else {
        ElMessage.error(res.errMsg)
    }
    
}
//楼栋信息
//图片上传
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
) => {
    console.log(response);
    if (response.errCode === 10000) {
        addForm.photo = response.data;
    }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('图片需要是jpg或png格式!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片不能超过2MB!')
        return false
    }
    return true
}

const emit = defineEmits(['close','update'])
const dialogVisible = ref(true)

let addForm = reactive<stafftype>({
    id:       0,
    name:     "",
    photo:    "",
    type:     null ,
    sex:      0 ,
    mobile:   "",
    cardid:   "",
    pass:     "",
    state:    0,
    building: []
})
const handleClose = () => {
    dialogVisible.value = false
    emit('close', [])
}



const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入姓名'))
  }  else {
    callback()
  }
}

const ruleForm = reactive({
  name: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
  name: [{ validator: validatePass2, trigger: 'blur' }],
})

let buildid:number[] = []


onMounted(()=>{
    getstafftypes()
    console.log(sessionStorage.getItem("token"));
    if (porps.addForm.id) {
       addForm= Object.assign(addForm,porps.addForm)
       buildid=addForm.building?.map((item:any)=>{
        return item.buildingid
       }) as number[]
    }
})
</script>

<style lang="less" scoped>
@import url(../assets/userinfo/userinfoadd.less);
</style>
